<template>
  <div class="auth-container no-footer">
    <!-- 左侧品牌区域 -->
    <div class="brand-section">
      <div class="brand-content">
        <h1 class="animate__animated animate__flash">MicroInvest</h1>
        <p class="brand-subtitle">智能投资的未来，从这里开始</p>
        <img src="@/assets/background.webp" alt="Logo" class="brand-logo" />
      </div>

    </div>

    <!-- 右侧认证区域 -->
    <div class="auth-section">
      <div class="auth-content">
        <!-- 标题区域 -->
        <div class="auth-header">
          <h1 style="color: #1c1c1c">{{ isLogin ? '登录' : '创建账号' }}</h1>
<!--          <p>{{ isLogin ? '请选择登录方式' : '开始您的投资之旅' }}</p>-->
        </div>

        <!-- 登录表单 -->
        <template v-if="isLogin">
          <div class="auth-tabs">
            <span
                :class="['tab', { active: loginMethod === 'password' }]"
                @click="loginMethod = 'password'"
            >密码登录</span>
            <span
                :class="['tab', { active: loginMethod === 'code' }]"
                @click="loginMethod = 'code'"
            >验证码登录</span>
          </div>

          <!-- 密码登录表单 -->
          <el-form v-if="loginMethod === 'password'" :model="loginForm" :rules="loginRules" ref="loginFormRef">
            <el-form-item prop="userName">
              <el-input
                  v-model="loginForm.userName"
                  placeholder="用户名"
                  :prefix-icon="User"
              />
            </el-form-item>
            <el-form-item prop="password">
              <el-input
                  v-model="loginForm.password"
                  type="password"
                  placeholder="密码"
                  :prefix-icon="Lock"
                  show-password
              />
            </el-form-item>
            <div class="form-actions">
              <el-button type="primary" class="submit-btn" @click="handlePasswordLogin">登录</el-button>
            </div>
          </el-form>

          <!-- 验证码登录表单 -->
          <el-form v-else :model="codeLoginForm" :rules="codeLoginRules" ref="codeLoginFormRef">
            <el-form-item v-if="!isCodeSent" prop="email">
              <el-input
                  v-model="codeLoginForm.email"
                  placeholder="邮箱"
                  :prefix-icon="Message"
              />
            </el-form-item>
            <el-form-item v-if="isCodeSent" prop="code">
              <VerificationCodeInput
                v-model="codeLoginForm.code"
                @complete="handleCodeLogin"
              />
            </el-form-item>
            <div class="form-actions">
              <el-button 
                type="primary" 
                class="submit-btn" 
                :disabled="isCodeSending"
                @click="sendLoginCode"
              >
                <template v-if="isCodeSending">
<!--                  <el-icon class="is-loading"><Loading /></el-icon>-->
                  {{ countdown }}s后重新发送
                </template>
                <template v-else>
                  {{ isCodeSent ? '重新获取验证码' : '获取验证码' }}
                </template>
              </el-button>
            </div>
          </el-form>
        </template>


        <!-- 底部切换 -->
        <div class="auth-footer">
          <p>
            {{ isLogin ? '还没有账号？' : '已有账号？' }}
            <el-button link type="primary" @click="toggleAuthMode">
              {{ isLogin ? '立即注册' : '去登录' }}
            </el-button>
          </p>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import {ref, reactive, onMounted} from 'vue'
import {  Lock, Message,User } from '@element-plus/icons-vue'
import router from "@/router";
// import '../../../../../node_modules/animate.css/animate.css';
import 'animate.css'
import { useTokenStore } from "@/stores/token.js"
import {usersLoginService, usersUseEmailLoginStepOneService, usersUseEmailLoginStepTwoService} from "@/api/user/users";
import VerificationCodeInput from '@/components/VerificationCodeInput.vue'
import toast from "@/utils/toast";
// 状态管理
const isLogin = ref(true)
const loginMethod = ref('password')
const isCodeSending = ref(false)
const isCodeSent = ref(false)
const countdown = ref(60)
// 表单引用
const loginFormRef = ref(null)
const codeLoginFormRef = ref(null)


// 表单数据
const loginForm = reactive({
  userName: '',
  password: ''
})

const codeLoginForm = reactive({
  email: '',
  code: ''
})
// 登录表单验证规则
const loginRules = {
  userName: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
};

const codeLoginRules = {
  email: [{ required: true, message: '请输入邮箱', trigger: 'blur' }],
  code: [{ required: true, message: '请输入验证码', trigger: 'blur' }]
};

onMounted(()=>{
  if(useTokenStore().hasToken){
    router.push('/center/findStock')
  }
});
//邮箱表单验证方法
const validateEmail = (formRef) => {
  const email = formRef.email;
  if (!email) {
    toast.warning("邮箱输入为空");
    return false;
  } else if (!/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(email)) {
    toast.warning('请输入正确的邮箱格式');
    return false;
  }
  return true;
}

// 通用表单验证方法
const validateForm = async (formRef) => {
  if (!formRef.value) return false
  try {
    await formRef.value.validate()
    return true
  } catch (error) {
    return false
  }
}

//用户名登录功能
const handlePasswordLogin = async () => {
  // 表单验证
  if (!await validateForm(loginFormRef)) {
    toast.warning("请正确输入所有信息")
    return;
  }

  // 发送登录请求
  const { code, message, data } = await usersLoginService(loginForm);

  if (code === 200) {

    toast.success('登录成功')
    useTokenStore().setToken(data);
    localStorage.setItem('afterLoginRedirect', '/center');
    window.location.reload();

  } else {
    toast.error(message || '登录失败');
  }
};

//邮箱登录功能
const sendLoginCode = async () => {
  // 校验邮箱格式
  if (!validateEmail(codeLoginForm)) {
    return;
  }

  // 立刻反馈，告诉用户「发送中」
  toast.info('验证码发送中，请稍候...');

  // 开始按钮倒计时
  startCountdown();

  // 发送验证码
  const { code, message } = await usersUseEmailLoginStepOneService(codeLoginForm.email);

  if (code === 200) {
    toast.success('验证码发送成功');
    isCodeSent.value = true;
  } else {
    toast.error(message || '验证码发送失败');
    // 如果失败了，也可以把倒计时停掉（可选）
    isCodeSending.value = false;
  }
}

//邮箱登录第二部
const handleCodeLogin = async (code) => {
  try {
    const { code: responseCode, message, data } = await usersUseEmailLoginStepTwoService({
      email: codeLoginForm.email,
      code: code
    });

    if (responseCode === 200) {
      toast.success('登录成功');
      useTokenStore().setToken(data);
      localStorage.setItem('afterLoginRedirect', '/center');
      window.location.reload();
    } else {
      toast.error(message || '登录失败');
    }
  } catch (error) {
    toast.error('登录失败，请稍后重试');
  }
}

// 切换登录/注册模式
const toggleAuthMode = () => {
   router.push('/user/register')
}

// 发送验证码倒计时
const startCountdown = () => {
  isCodeSending.value = true
  countdown.value = 60
  const timer = setInterval(() => {
    countdown.value--
    if (countdown.value <= 0) {
      clearInterval(timer)
      isCodeSending.value = false
    }
  }, 1000)
}

</script>

<style lang="scss" scoped>
@import '../../../assets/styles/theme/auth';

</style>